package com.luck.pf.util;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ConfigUtil {
	private static DocumentBuilderFactory factory;
	private static DocumentBuilder builder;
	private Document doc;
	private Element root;
	private String file;

	public ConfigUtil(String file) throws IOException {
		this.file = file;
		loadXMLParser();

	}

	private void loadXMLParser() throws IOException {
		if (builder == null) {
			try {
				factory = DocumentBuilderFactory.newInstance();
				builder = factory.newDocumentBuilder();
			} catch (ParserConfigurationException ex) {
				throw new IOException("XML Parser load error:"
						+ ex.getLocalizedMessage());
			}
		}
		try {
			doc = builder.parse(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(file));
		} catch (Exception e) {
		}
		root = doc.getDocumentElement();
		if (!"config".equals(root.getNodeName())) {
			throw new IOException("Config file format error, root node must be <config>");
		} else {
			return;
		}
	}

	public String get(String key, String def) {
		if (key == null) {
			throw new NullPointerException("parameter key is null");
		}
		Node node = findNode(key);
		if (node == null) {
			return def;
		}
		NodeList nl = node.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			if (nl.item(i).getNodeType() == 3) {
				return nl.item(i).getNodeValue().trim();
			}
		}
		node.appendChild(doc.createTextNode(def));
		return def;
	}

	private Node findNode(String key) {
		Node ancestor = root;
		for (StringTokenizer st = new StringTokenizer(key, "/"); st.hasMoreTokens();) {
			String nodeName = st.nextToken();
			NodeList nl = ancestor.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node n = nl.item(i);
				if (!nodeName.equals(n.getNodeName())) {
					continue;
				}
				ancestor = n;
				if (!st.hasMoreTokens()) {
					return n;
				}
				break;
			}

		}
		return null;
	}
}
